package com.timecheck.service;

import com.alibaba.fastjson.JSONObject;
import com.timecheck.pojo.DataResult;
import com.timecheck.pojo.TimeCheck;
import com.timecheck.repository.TimeCheckRepository;
import com.timecheck.util.HttpClientUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TimeCheckService {

    @Autowired
    private TimeCheckRepository timeCheckRepository;

    @Autowired
    private Environment environment;
    @Scheduled(cron = "${jhsec.time.check.timeinterval}")
    public void timeCheck() {
        try {

            String protocol = environment.getProperty("protocol");
            String f5Path = environment.getProperty("f5_path");
            String center = environment.getProperty("center");
            String uid = environment.getProperty("uid");

            String[] f5Paths = f5Path.split(";");

            String[] centers = center.split(";");

            HashMap<String, String> map = new HashMap<>();

            List<String> f5PathList = new ArrayList<>(Arrays.asList(f5Paths));

            List<String> centerList = new ArrayList<>(Arrays.asList(centers));

            for (int i = 0; i < f5PathList.size(); i++) {
                if(!StringUtils.isEmpty(f5PathList.get(i))){
                    map.putIfAbsent(f5PathList.get(i), centerList.get(i));
                }
            }

            for (String f5 : f5PathList) {
                if(!StringUtils.isEmpty(f5)){
                    String url = protocol + "://" + f5 + "/iam-web/oauthc/time/check";
                    Long beginTime = System.currentTimeMillis();
                    String rvStr = null;
                    rvStr = HttpClientUtil.httpPost(url, JSONObject.toJSONString(uid));
                    Long endTime = System.currentTimeMillis();

                    String responseTime = String.format("%.3f", (endTime - beginTime) / 1000.0) + "秒";
                    TimeCheck timeCheck = new TimeCheck();
                    if (rvStr.contains("调用接口异常") || rvStr.contains("结果为null")){
                        timeCheck.setRv("请求失败");
                    }else {
                        timeCheck.setRv("请求成功");
                    }
                    timeCheck.setId(UUID.randomUUID().toString());
                    timeCheck.setBeginTime(beginTime);
                    timeCheck.setResponseTime(responseTime);
                    timeCheck.setCenter(map.get(f5));
                    timeCheckRepository.saveTimeCheck(timeCheck);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
